package com.advertisementsystem.handler;

import com.advertisementsystem.Dto.ChatMessageDTO;
import com.advertisementsystem.Servie.ChatService;
import com.advertisementsystem.entity.ChatMessages;
import com.advertisementsystem.utils.RedisCache;
import com.advertisementsystem.vo.MessageResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.awt.*;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class ChatWebSocketHandler extends TextWebSocketHandler {

    // @Autowired
    // private ChatService chatService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RedisCache redisCache;

    private static final Map<Long, WebSocketSession> userSessions = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        Long userId = getUserId(session);
        userSessions.put(userId, session);
        markUserOnline(userId);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

    }
    public void sendNotification(Long userId, Object notification) {
        log.info("{}",notification);
        WebSocketSession session = userSessions.get(userId);
        if (session != null && session.isOpen()) {
            try {
                objectMapper.registerModule(new JavaTimeModule());
                String message = objectMapper.writeValueAsString(notification);
                session.sendMessage(new TextMessage(message));
                log.info("Notification sent to user: {}", userId);
                log.info("发送消息：{}", message);
            } catch (IOException e) {
               log.error("Error sending notification to user: {}", userId, e);
            }
        } else {
            log.info("User {} is not connected, notification not sent", userId);
        }
    }


    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        Long userId = getUserId(session);
        userSessions.remove(userId);
        markUserOffline(userId);
    }

    private Long getUserId(WebSocketSession session) {
        return Long.parseLong(session.getAttributes().get("userId").toString());
    }

    private void markUserOnline(Long userId) {
        redisCache.setCacheObject("online_users:" + userId, "true", 24, TimeUnit.HOURS);
    }

    private void markUserOffline(Long userId) {
        redisCache.deleteObject("online_users:" + userId);
        // redisTemplate.delete("online_users:" + userId);
    }
}
